package com.d3sq.common.resolvers;

import java.util.List;

import javax.core.common.utils.ToolKit;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.d3sq.common.constants.ExplorerConstant;
import com.d3sq.common.listeners.UploadListener;


/**
 * 文件上传进度响应
 *
 */
public class UploadResolver extends CommonsMultipartResolver {
	
	@Override
	public MultipartParsingResult parseRequest(HttpServletRequest request)
			throws MultipartException {
		String progressId = ToolKit.getString(request, "X-Progress-ID");
		String encoding = determineEncoding(request);
		FileUpload fileUpload = prepareFileUpload(encoding);
		UploadListener listener = new UploadListener(progressId);
		fileUpload.setProgressListener(listener);
		request.getSession().setAttribute(ExplorerConstant.PROGRESS_KEY_SUFF + progressId, listener);
		try {
			List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
			return parseFileItems(fileItems, encoding);
		}
		catch (FileUploadBase.SizeLimitExceededException ex) {
			throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
		}
		catch (FileUploadException ex) {
			throw new MultipartException("无法解析此请求", ex);
		}
	}
	
}
